var width = 240,
    height = 160;
var x0, y0, xA, yA;

//初始化
function init() {
    var target = document.getElementById('target');

    var min = 1 / 6;
    var max = 5 / 6;

    //固定点
    // x0 = width * min,
    // y0 = height / 2,
    // xA = [ width * max, width / 2 ],
    // yA = [ height * min, height * max ];

    //随机点
    x0 = Math.random() * (width - 40) + 20;
    y0 = Math.random() * (height - 40) + 20;
    xA = [];
    yA = [];
    for(var i = 0; i < 3; i += 1) {
        xA.push(Math.random() * (width - 40) + 20);
        yA.push(Math.random() * (height - 40) + 20);
    }

    target.appendChild( createPath('Linear', TWEEN.Interpolation.Linear) );
    target.appendChild( createPath('Bezier', TWEEN.Interpolation.Bezier) );
    target.appendChild( createPath('CatmullRom', TWEEN.Interpolation.CatmullRom) );
}

function createPath(title, interpolation) {
    var div = document.createElement('div');
    div.style.display = 'inline-block';
    div.style.width = width + 20 + 'px';
    div.style.height = height + 20 + 'px';

    var canvas = document.createElement('canvas');
    canvas.width = width;
    canvas.height = height;
    var ctx = canvas.getContext('2d');

    ctx.fillStyle = 'rgb(250, 250, 250)';
    ctx.fillRect(0, 0, width, height);

    ctx.fillStyle = 'rgb(200, 200, 200)';
    ctx.fillRect(x0 - 3, y0 - 3, 6, 6);
    ctx.fillRect(xA[xA.length - 1] - 3, yA[yA.length - 1] - 3, 6, 6);

    for(var i = 0; i < xA.length; i += 1) {
        ctx.fillRect(xA[i] - 2, yA[i] - 2, 4, 4);
    }

    ctx.strokeStyle = 'rgb(255, 127, 127)';
    ctx.lineWidth = 2;

    var obj = { x: x0, y: y0, old: { x: x0, y: y0 }};

    //用数组作为变化数据
    new TWEEN.Tween(obj).to({x: xA, y: yA}, 3000).delay(250).easing(TWEEN.Easing.Linear.None).interpolation(interpolation).onUpdate(function(obj) {
        ctx.beginPath();
        ctx.moveTo(obj.old.x, obj.old.y)
        ctx.lineTo(obj.x, obj.y)
        ctx.closePath();
        ctx.stroke();

        obj.old.x = obj.x;
        obj.old.y = obj.y;
    }).start();

    div.appendChild(document.createTextNode(title));
    div.appendChild(canvas);
    return div;
}

//动画函数
function animate() {
    var id = requestAnimationFrame(animate);

    var result = TWEEN.update();

    if(!result) cancelAnimationFrame(id);
}

init();
animate();